package com.ruoyi.community.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.community.dto.CommunityPostQueryDto;
import com.ruoyi.community.vo.CommunityListVo;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.community.domain.CommunityPost;
import com.ruoyi.community.service.ICommunityPostService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 社区帖子Controller
 *
 * @author ruoyi
 * @date 2025-05-22
 */
@RestController
@RequestMapping("/community")
public class CommunityPostController extends BaseController {
    @Autowired
    private ICommunityPostService communityPostService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询社区帖子列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CommunityPostQueryDto communityPost) {
        List<CommunityListVo> res = new ArrayList<>();
        LoginUser loginUser = getLoginUser();
        Long userId = loginUser.getUser().getUserId();
        if (communityPost.isSelectMe()) {
            // 只筛选自己的
            communityPost.setUserId(userId);
        }
        List<CommunityPost> list = communityPostService.selectCommunityPostList(communityPost);
        if (CollectionUtil.isNotEmpty(list)) {
            List<Long> userIdList = list.stream().map(CommunityPost::getUserId)
                    .distinct().collect(Collectors.toList());
            List<SysUser> sysUserList = sysUserService.selectUserByIds(userIdList);
            Map<Long, SysUser> userMap = sysUserList.stream()
                    .collect(Collectors.toMap(SysUser::getUserId, Function.identity()));
            list.forEach(item -> {
                CommunityListVo communityListVo = new CommunityListVo();
                SysUser user = userMap.get(item.getUserId());
                if (user != null) {
                    communityListVo.setUserId(user.getUserId());
                    communityListVo.setNickName(user.getNickName());
                    communityListVo.setAvatar(user.getAvatar());
                    boolean equals = user.getUserId().equals(userId);
                    communityListVo.setMe(equals);
                }
                communityListVo.setCommunityPost(item);
                res.add(communityListVo);
            });
        }
        return getDataTable(res);
    }

    /**
     * 导出社区帖子列表
     */
    @PreAuthorize("@ss.hasPermi('community:community:export')")
    @Log(title = "社区帖子", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CommunityPost communityPost) {
        List<CommunityPost> list = communityPostService.selectCommunityPostList(communityPost);
        ExcelUtil<CommunityPost> util = new ExcelUtil<CommunityPost>(CommunityPost.class);
        util.exportExcel(response, list, "社区帖子数据");
    }

    /**
     * 获取社区帖子详细信息
     */
    @PreAuthorize("@ss.hasPermi('community:community:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(communityPostService.selectCommunityPostById(id));
    }

    /**
     * 新增社区帖子
     */
    @Log(title = "社区帖子", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CommunityPost communityPost) {
        LoginUser loginUser = getLoginUser();
        Long userId = loginUser.getUser().getUserId();
        if (!StringUtils.hasText(communityPost.getContent())) {
            throw new ServiceException("动态内容不能为空");
        }
        communityPost.setUserId(userId);
        communityPost.setGoods(0L);
        communityPost.setPostTime(new Date());
        communityPost.setCommentNumber(0L);
        return toAjax(communityPostService.insertCommunityPost(communityPost));
    }

    /**
     * 修改社区帖子
     */
    @PreAuthorize("@ss.hasPermi('community:community:edit')")
    @Log(title = "社区帖子", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CommunityPost communityPost) {
        return toAjax(communityPostService.updateCommunityPost(communityPost));
    }

    /**
     * 删除社区帖子
     */
    @PreAuthorize("@ss.hasPermi('community:community:remove')")
    @Log(title = "社区帖子", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(communityPostService.deleteCommunityPostByIds(ids));
    }


    @Anonymous
    @Log(title = "点赞", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/liked/{id}")
    @ApiOperation(value = "点赞接口", notes = "需要评论id,点赞用户的userId,data的返回值2表示点赞成功!,1表示取消点赞成功,0表示系统异常")
    public AjaxResult liked(@PathVariable("id") Long id) {
        return success(communityPostService.liked(id));
    }
}
